﻿using DataModels.Dto;
using DataModels.Dto.AuthCore;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.Bill;
using Dm;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic;
using SqlSugar;
using System.Reflection.Emit;
using System.Transactions;
using static DataModels.Enums.AuthCore.UserEnum;
using static DataModels.Enums.GeneralEnum;

namespace Services.AuthCore
{
    public class UserService(SqlSugarClient db) : BaseService(db)
    {
        // 获取用户信息
        public ResponseModel GetUserInfo()
        {
            Customer usermodel = db.Queryable<Customer>().Where(u => u.UUID == UserUUID && u.CustStatus == "1").First();
            if (usermodel == null)
            {
                return Error("用户不存在");
            }
            usermodel.Phone = usermodel.Tel1;
            return Success(usermodel);
        }

        // 修改用户信息
        public ResponseModel EditUserInfo(EditUserInfo userinfo)
        {
            try
            {
                Customer model = db.Queryable<Customer>().Where(u => u.UUID == userinfo.UUID && u.CustStatus == "1").First();
                if (model == null)
                {
                    return Error("用户不存在");
                }
                // 更新用户信息
                if (!string.IsNullOrEmpty(userinfo.AvatarUrl))
                    model.PicUrl = userinfo.AvatarUrl;

                if (!string.IsNullOrEmpty(userinfo.DisplayName))
                    model.Name = userinfo.DisplayName;

                if (userinfo.Birthday != DateTime.MinValue)
                    model.Birthday = userinfo.Birthday;

                model.Sex = (int)userinfo.Gender;
                db.Updateable(model).ExecuteCommand();
                return Success();
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }
        
        // 获取商户用户信息
        public ResponseModel GetMerchantsUserInfo()
        {
            User usermodel = db.Queryable<User>().Where(u => u.UUID == UserUUID).First();
            if (usermodel == null)
            {
                return Error("用户不存在");
            }
            return Success(usermodel);
        }

        // 修改商户用户信息
        public ResponseModel EditMerchantsUserInfo(EditUserInfo userinfo)
        {
            try
            {
                User model = db.Queryable<User>().Where(u => u.UUID == userinfo.UUID).First();
                if (model == null)
                {
                    return Error("用户不存在");
                }
                // 更新用户信息
                if (!string.IsNullOrEmpty(userinfo.AvatarUrl))
                    model.AvatarUrl = userinfo.AvatarUrl;

                if (!string.IsNullOrEmpty(userinfo.DisplayName))
                    model.DisplayName = userinfo.DisplayName;

                if (userinfo.Birthday != DateTime.MinValue)
                    model.Birthday = userinfo.Birthday;

                model.Gender = userinfo.Gender;
                db.Updateable(model).ExecuteCommand();
                return Success();
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
        }

        /// <summary>
        /// 获取地址信息
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseModel> GetDeliveryAddress()
        {
            var res = await db.Queryable<DeliveryAddress>()
                .Where(u => u.UserUUID == UserUUID && u.IsDeleted == DataModels.Enums.GeneralEnum.Status.Disable)
                .Select(u => new
                {
                    u.UUID,
                    u.ContactPerson,
                    u.ContactPhone,
                    u.Province,
                    u.City,
                    u.District,
                    u.AddressDetail,
                    u.ZipCode,
                    u.AddressTag,
                    u.Longitude,
                    u.Latitude,
                    u.IsDefault
                })
                .ToListAsync();
            return Success(res);
        }

        /// <summary>
        /// 添加收货地址
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ResponseModel> AddDeliveryAddress(AddDeliveryAddress info)
        {
            DeliveryAddress da = new()
            {
                ContactPerson = info.ContactPerson,
                ContactPhone = info.ContactPhone,
                Province = info.Province,
                City = info.City,
                District = info.District,
                AddressDetail = info.AddressDetail,
                ZipCode = info.ZipCode,
                AddressTag = info.AddressTag,
                Longitude = info.Longitude,
                Latitude = info.Latitude,
                UserUUID = UserUUID
            };
            bool dac = await db.Queryable<DeliveryAddress>()
                .Where(da => da.UserUUID == UserUUID)
                .Where(da => da.IsDeleted == Status.Disable)
                .AnyAsync();
            if (!dac)
            {
                da.IsDefault = Status.Enable;
            }
            da = await db.Insertable(da).ExecuteReturnEntityAsync();
            if (info.IsDefault == Status.Enable)
            {
                await SetDefaultDeliveryAddress(da.UUID);
            }
            return Success(da);
        }

        /// <summary>
        /// 修改地址
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ResponseModel> SetDeliveryAddress(AddDeliveryAddress info)
        {
            DeliveryAddress da = await db.Queryable<DeliveryAddress>()
                .Where(da => da.UserUUID == UserUUID)
                .Where(da => da.IsDeleted == Status.Disable)
                .Where(da => da.UUID == info.UUID)
                .FirstAsync();

            if(da == null)
            {
                return Error("地址不存在");
            }
            da.ContactPerson = info.ContactPerson;
            da.ContactPhone = info.ContactPhone;
            da.Province = info.Province;
            da.City = info.City;
            da.District = info.District;
            da.AddressDetail = info.AddressDetail;
            da.ZipCode = info.ZipCode;
            da.IsDefault = info.IsDefault;
            da.AddressTag = info.AddressTag;
            da.Longitude = info.Longitude;
            da.Latitude = info.Latitude;
            da.UpdateTime = DateTime.Now;

            if (info.IsDefault == Status.Enable)
            {
                await SetDefaultDeliveryAddress(da.UUID);
            }
            return Success("修改成功");

        }
        
        /// <summary>
        /// 删除地址
        /// </summary>
        /// <param name="UUID"></param>
        /// <returns></returns>
        public async Task<ResponseModel> DelDeliveryAddress(Guid UUID)
        {
            await db.Updateable<DeliveryAddress>()
                .Where(da => da.IsDeleted == Status.Disable)
                .Where(da => da.UUID == UUID)
                .SetColumns(da => new DeliveryAddress { IsDeleted = Status.Enable, UpdateTime = DateTime.Now })
                .ExecuteCommandAsync();
                ;
            return Success("删除成功");
        }

        private async Task<bool> SetDefaultDeliveryAddress(Guid uuid)
        {
            try
            {
                // 先将当前用户的其他地址设为非默认
                var rowsUpdated = await db.Updateable<DeliveryAddress>()
                    .Where(da => da.IsDeleted == Status.Disable)
                    .Where(da => da.UserUUID == UserUUID)
                    .Where(da => da.UUID != uuid)
                    .SetColumns(da => new DeliveryAddress { IsDefault = Status.Disable, UpdateTime = DateTime.Now })
                    .ExecuteCommandAsync();

                // 再将指定地址设为默认
                var result = await db.Updateable<DeliveryAddress>()
                    .SetColumns(da => new DeliveryAddress { IsDefault = Status.Enable, UpdateTime = DateTime.Now })
                    .Where(da => da.UUID == uuid)
                    .Where(da => da.UserUUID == UserUUID)
                    .Where(da => da.IsDeleted == Status.Disable)
                    .ExecuteCommandAsync();

                // 返回操作是否成功
                return result > 0;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        /// <summary>
        /// 获取优惠券列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ResponseModel> GetPaymentCoupon(GetPaymentCouponInfo info)
        {
            List<PaymentCouponMap> pcm = await db.Queryable<PaymentCouponMap, PaymentCoupon>((pcm, pc) => new JoinQueryInfos(
                    JoinType.Left, pcm.PaymentCouponUUID == pc.UUID
                ))
                .Where(pcm => pcm.IsUsed == info.IsUsed)
                .WhereIF(info.IsExpire == Status.Enable,pcm => pcm.EndTime <= DateTime.Now)
                .WhereIF(info.IsExpire == Status.Disable,pcm => pcm.EndTime > DateTime.Now)
                .ToListAsync()
                ;
            return Success(pcm);
        }

        /// <summary>
        /// 通过角色名获取用户（业主）
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public  ResponseModel GetObtainUsers_owners_through_role(string crolename)
        {
            List<Customer> pcm =  db.Queryable<Customer, Dncuserrolemapping,Dncrole>((c, dl,dr) => new JoinQueryInfos(
                    JoinType.Inner, c.UUID ==dl.UserGuid,
                    JoinType.Inner, dl.RoleCode ==dr.Code
                ))
                .WhereIF(!string.IsNullOrWhiteSpace(crolename), (c, dl, dr) => dr.Name==crolename)

                .Select((c) => new Customer
                {
                    UUID = c.UUID,
                    Name = c.Name,
                    Tel1 = c.Tel1,
                    mpopen_id = c.mpopen_id,
                })
                .ToList()
                ;
            return Success(pcm);
        }


        /// <summary>
        /// 当前人员是否为指定角色
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel WhetherPersonSpecifiedRole(string RoleName)
        {
            bool isdui = false;
            ResponseModel rm2 = GetObtainUsers_owners_through_role(RoleName);
            if (rm2.Data != null)
            {
                List<Customer> pcm2 = (List<Customer>)rm2.Data;
                if (pcm2.Where(p => p.UUID == UserUUID).FirstOrDefault() != null)
                {
                    isdui = true;
                }
            }

            return Success(isdui);
        }

    }
}
